<?php 
	
	include_once "achievement_model.php";
	include_once "user_model.php";
		
	class Post_Model {
		
		//mengembalikan id post yang barusan di insert, jika gagal, mengembalikan false
		public function insertPost($title, $post_type, $poster_id, $content) {
			$ret = mysql_query("INSERT INTO post (title, post_type, poster_id, datetime, content ) 
						VALUES ('$title', '$post_type', '$poster_id', NOW(), '$content')" ) or die('mysql_error : '.mysql_error());
			
			$post_id = mysql_insert_id(); // dapetin post id barusan		
			
			if(!$ret) // jika gagal
				return $ret;//false
			
			//otomatis dapet achivement post pertama
			$achievement_model = new Achievement_Model();
			$achievement_model->addAchievementToUser($poster_id, Achievement_Model::POST_ONCE);
						
			$user_model = new User_Model();
			
			//naikin post count
			$user_model->incUserPostCount($poster_id);			
			
			//jika diatas 10 kali
			$user_res = $user_model->getUserInfo($poster_id);			
			$user_row = mysql_fetch_array($user_res);
			if($user_row["post_count"] >= 10) {
				$achievement_model->addAchievementToUser($poster_id, Achievement_Model::POST_10);
			}
			
			return $post_id;
		}
		
		public function getPost($post_id) {
			$res = mysql_query("SELECT *, post.comment_count AS post_comment_count, post.like_count AS post_like_count 
						FROM post 												
						INNER JOIN user
						ON user.ID=poster_id
						WHERE post.ID=$post_id 
						LIMIT 1") or die(mysql_error());
			return $res;
		}
		
		public function getUserPosts($user_id) {
			$res = mysql_query("SELECT * 
						FROM post 												
						INNER JOIN user
						ON user.ID=poster_id
						WHERE user.ID=$user_id
						ORDER BY post.datetime desc") or die(mysql_error());
			return $res;
		}
		
		public function getUserIdByUsername($username)
		{
			$res = mysql_query("SELECT ID
										   FROM user
										   WHERE username = '$username'") or die(mysql_error());	
			return $res;
		}		
		
		public function incPostCommentCount($post_id) {
			$ret = mysql_query("UPDATE post
								SET comment_count=comment_count+1
								WHERE ID=$post_id") or die(mysql_error());	
			return $ret;
		}
		
		public function decPostCommentCount($post_id) {
			$ret = mysql_query("UPDATE post
								SET comment_count=comment_count-1
								WHERE ID=$post_id") or die(mysql_error());	
			return $ret;
		}
		
		public function incrementLike($post_id)
		{
			$update = "UPDATE post SET like_count=(like_count+1) WHERE ID= '$post_id'";
															
			return $update;
		}
		
		public function decrementLike($post_id)
		{
			$update = "UPDATE post SET like_count = (like_count-1) WHERE ID= '$post_id'";
			return $update;
		}
		
		public function getLikeOrDislike($user_id,$post_id)
		{
			$q = "SELECT * FROM post_who_like 
					 WHERE user_id='$user_id' 
					 AND post_id='$post_id'";
			$res = mysql_query($q) or die(mysql_error());
			$res_ar = mysql_fetch_array($res);
			
			return $res_ar["like_or_dislike"];
		}
		
		public function fetchLikeQuery($update,$post_id, $user_id,$op)
		{
			$res = "SELECT like_count FROM post WHERE post.ID = '$post_id'";
			mysql_query($update) or die(mysql_error());//query unutuk update
			$temp = mysql_query($res) or die(mysql_error());
			$this->insertToLikeRelation($user_id,$post_id,$op);
			$liketemp = mysql_fetch_array($temp);
			
			echo "You've $op"."d this ($liketemp[like_count] people like this)";
			if($op == "like") {
				$achievement_model = new Achievement_Model();			
				$post_res = $this->getPost($post_id);					
				
				//jika post ini sudah dilike sebanyak 100 kali, yang ngepost dapet achievement		
				$post_row = mysql_fetch_array($post_res);				
				if($post_row["like_count"]>=100) {				
					$achievement_model->addAchievementToUser($post_row["poster_id"], Achievement_Model::ONE_POST_100_LIKES);
				}				
			}else{
				$achievement_model = new Achievement_Model();			
				$post_res = $this->getPost($post_id);					
				
				//jika post ini sudah di-dislike sebanyak 100 kali, yang ngepost dapet achievement		
				$post_row = mysql_fetch_array($post_res);				
				if($post_row["like_count"]<=-100) {				
					$achievement_model->addAchievementToUser($post_row["poster_id"], Achievement_Model::ONE_POST_100_DISLIKES);
				}				
			}
			
		}
		
		private function insertToLikeRelation($user_id,$post_id,$op)
		{
			$q ="INSERT INTO progin_171_13509047.post_who_like (post_id, user_id, like_or_dislike) 
					VALUES ('$post_id', '$user_id', '$op')";
			mysql_query($q) or die(mysql_error());
		}
		
		public function isPostLikedByUser($user_id,$post_id)
		{
			$q = "SELECT * FROM post_who_like 
					 WHERE user_id='$user_id' 
					 AND post_id='$post_id'";
			$ret = mysql_query($q) or die (mysql_error());
			$haslike = (mysql_num_rows($ret) > 0)? true:false; //false jika user belum melike post tersebut
			
			return $haslike;
		}
		
		public function isUserOperationSame($user_id,$post_id,$op)
		{
			$q = "SELECT * FROM post_who_like 
					 WHERE user_id='$user_id' 
					 AND post_id='$post_id' AND like_or_dislike='$op'";
			$ret = mysql_query($q) or die (mysql_error());
			$issame =  (mysql_num_rows($ret) > 0)? true:false; //false jika operasi pada suatu post tidak sama
			
			return $issame;
		}
		
		public function neutralizeLikeCount($user_id,$post_id,$op)
		{
			$q = "DELETE FROM post_who_like 
					 WHERE user_id='$user_id' 
					 AND post_id='$post_id'";
			$q_net = ($op=="like")? $this->decrementLike($post_id):$this->incrementLike($post_id);
			$q_like_count = "SELECT like_count
									  FROM post
									  WHERE post.ID='$post_id'";

			mysql_query($q) or die(mysql_error());//delete dari  relasi like
			mysql_query($q_net) or die(mysql_error());//netralkan jumlah like
			$likecount = mysql_query($q_like_count) or die(mysql_error());
			$liketemp = mysql_fetch_array($likecount);

			return  $liketemp["like_count"]." people like this";

		}
		
		public function printLike($likecount,$user_id,$post_id)
		{
			$q = "SELECT * FROM post_who_like 
					 WHERE user_id='$user_id' 
					 AND post_id='$post_id'";
			if($this->isPostLikedByUser($user_id,$post_id))
			{
				$ret = mysql_query($q) or die (mysql_error());
				$res = mysql_fetch_array($ret);
				echo "<small><i id=\"content-like-$post_id\">You've $res[like_or_dislike]"."d this ($likecount people like this)</i></small>";
			}
			else
			{
				echo "<small><i id=\"content-like-$post_id\">".$likecount."  people like this</i></small>";
			}
		}
		
		public function printLikeWithClass($likecount,$user_id,$post_id)
		{
			$q = "SELECT * FROM post_who_like 
					 WHERE user_id='$user_id' 
					 AND post_id='$post_id'";
			if($this->isPostLikedByUser($user_id,$post_id))
			{
				$ret = mysql_query($q) or die (mysql_error());
				$res = mysql_fetch_array($ret);
				echo "<small><i class=\"content-like-$post_id\">You've $res[like_or_dislike]"."d this ($likecount people like this)</i></small>";
			}
			else
			{
				echo "<small><i class=\"content-like-$post_id\">".$likecount."  people like this</i></small>";
			}
		}
		
		private function generateQueryForTag($tag)
		{
			if(strcmp($tag,"default") ==0)
			{
				return "SELECT type
							FROM post_tag 
							INNER JOIN post 
							ON post_tag.post_id =post.ID
							INNER JOIN tag
							ON tag.ID=post_tag.tag_id
							WHERE post.ID = $q[0]";
			}
			else
			{
				/* explode(","); */
			}
		}
		
		public function printRelevantTags($postid)
		{
			$query = "SELECT type
							FROM post_tag 
							INNER JOIN post 
							ON post_tag.post_id =post.ID
							INNER JOIN tag
							ON tag.ID=post_tag.tag_id
							WHERE post.ID = $postid";
			$res = mysql_query($query) or die(mysql_error());
			while($tag = mysql_fetch_array($res,MYSQL_BOTH))
				{
					echo "<a class =tags href=list-content.php?tag=$tag[type]>$tag[type]</a>";
				}
		}
		public function showAllTags()
		{
			$query = "SELECT type
							FROM tag";
							
			$res = mysql_query($query) or die(mysql_error());
			while($tag = mysql_fetch_array($res,MYSQL_BOTH))
				{
					echo "<a class =tags href=\"list-content.php?tag=$tag[type]\">$tag[type]</a>";
				}
		}
		
		public function doOperation($_operation)
		{
			$temp_op = explode("@",$_operation);
			$res="";
			if (strcmp($temp_op[0],"like") == 0)
				{$res = $this->incrementLike($temp_op[1]);}
			else if (strcmp($temp_op[0],"dislike") == 0)
				{$res = $this->decrementLike($temp_op[1]);}
			return $res;
		}
			
		public function getPostOrderedLimited($sortby, $limited) {
			$res = mysql_query("SELECT * , post.ID AS post_id, post.comment_count AS post_comment_count
								FROM post
								INNER JOIN user
								ON user.ID=poster_id
								ORDER BY $sortby DESC
								LIMIT $limited") or die(mysql_error());
			return $res;
		}				
			
		public function generateCountQuery($tag,$filtermode,$sortmode,$last,$maxinpage)
		{
			/* if(strcmp()) */
			$tempquery = "";
			str_replace("%20"," ",$tag);
			if(empty($filtermode)&&empty($sortmode)&&empty($tag))//default query
			{
				$tempquery = "SELECT * 
										FROM post  
										JOIN user
										WHERE post.poster_id=user.ID 
										ORDER BY post.datetime DESC";
			}
			else if(empty($filtermode)&&empty($sortmode)&&!empty($tag))//kasus 1 tag -- user mengklik link ke tag
			{
				$tempquery= "SELECT *
									FROM post
									INNER JOIN post_tag 
									ON post_tag.post_id =post.ID
									INNER JOIN tag
									ON tag.ID=post_tag.tag_id
									INNER JOIN user
									ON user.ID=post.poster_id
									WHERE tag.type = '$tag'
									ORDER BY post.datetime DESC";
			}
			else if(!empty($filtermode)&&!empty($sortmode)&&!empty($tag)) //pasti berisi tag
			{			
				$temptags = explode(",",$tag);
				$notclause="";
				$andclause = "GROUP BY post.ID";
				$tempfilter = "";
				$i=0;
				
				if (strcmp($filtermode,"AND") == 0)
				{
					$andclause= $clause. "GROUP BY post.ID
									HAVING COUNT(DISTINCT tag.type) = ".count($temptags);
				
				}
				else if (strcmp($filtermode,"NOT") == 0)
				{$notclause="NOT";}
				
				while($i < count($temptags)-1)
				{
					$tempfilter = $tempfilter."'".$temptags[$i]."',";
					$i++;
				}
				$tempfilter = $tempfilter."'".$temptags[$i]."'";
				$tempquery= "SELECT *
									FROM post
									INNER JOIN post_tag
									ON post_tag.post_id =post.ID
									INNER JOIN tag
									ON tag.ID=post_tag.tag_id
									INNER JOIN user
									ON user.ID=post.poster_id
									WHERE tag.type ".$notclause." IN (".$tempfilter.")
									".$andclause."
									ORDER BY post.".$sortmode." DESC";
			}
			return $tempquery;
		}
		
		public function generateQuery($tag,$filtermode,$sortmode,$last,$maxinpage)
		{
			/* if(strcmp()) */
			$tempquery = "";
			if(empty($filtermode)&&empty($sortmode)&&empty($tag))//default query
			{
				$tempquery = "SELECT * 
										FROM post  
										JOIN user
										WHERE post.poster_id=user.ID 
										ORDER BY post.datetime 
										DESC LIMIT $last,$maxinpage";
			}
			else if(empty($filtermode)&&empty($sortmode)&&!empty($tag))//kasus 1 tag -- user mengklik link ke tag
			{
				$tempquery= "SELECT *
									FROM post
									INNER JOIN post_tag
									ON post_tag.post_id =post.ID
									INNER JOIN tag
									ON tag.ID=post_tag.tag_id
									INNER JOIN user
									ON user.ID=post.poster_id
									WHERE tag.type = '$tag'
									GROUP BY post.ID
									ORDER BY post.datetime 
									DESC LIMIT $last,$maxinpage";
			}
			else if(!empty($filtermode)&&!empty($sortmode)&&!empty($tag)) //pasti berisi tag
			{
				$temptags = explode(",",$tag);
				$notclause="";
				$andclause = "GROUP BY post.ID";
				$tempfilter = "";
				$i=0;
				
				if (strcmp($filtermode,"AND") == 0)
				{
					$andclause= $clause. "GROUP BY post.ID
									HAVING COUNT(DISTINCT tag.type) = ".count($temptags);
				
				}
				else if (strcmp($filtermode,"NOT") == 0)
				{$notclause="NOT";}
				
				while($i < count($temptags)-1)
				{
					$tempfilter = $tempfilter."'".$temptags[$i]."',";
					$i++;
				}
				$tempfilter = $tempfilter."'".$temptags[$i]."'";
				$tempquery= "SELECT *
									FROM post
									INNER JOIN post_tag 
									ON post_tag.post_id =post.ID
									INNER JOIN tag
									ON tag.ID=post_tag.tag_id
									INNER JOIN user
									ON user.ID=post.poster_id
									WHERE tag.type ".$notclause." IN (".$tempfilter.")
									".$andclause."
									ORDER BY post.".$sortmode." 
									DESC LIMIT $last,$maxinpage";
			}
			return $tempquery;
		}

				
	}
			
	

?>